package com.duomi.lang;

import java.util.Arrays;

class Utils {
    static void except(String desc, boolean expression) {
        if (!expression) {
            throw new DuomiEvalException(desc);
        }
    }

    static <T> T exceptAs(Object obj, Class<T> tClass) {
        if (tClass.isInstance(obj)) {
            //noinspection unchecked
            return ((T) obj);
        }
        throw new DuomiEvalException("except Object Class: " + tClass + ", but get: " + obj.getClass());
    }

    static boolean bool(Object obj) {
        if (obj instanceof Boolean) {
            return (boolean) obj;
        }
        return true;
    }

    static void printSrcContext(String source, int row, int column) {

        System.out.println("exception happens in row = " + row + ", column = " + column);

        System.out.println("Exception Scene:");

        int index = 0;
        int curRow = 1;
        while (curRow < row) {
            final char c = source.charAt(index);
            if (c == '\n') {
                curRow++;
            }

            index += 1;
        }

        final int start = index;
        while (index < source.length() && source.charAt(index) != '\n') {
            index++;
        }
        final int end = index;

        System.out.print('"');
        System.out.print(source.substring(start, end));
        System.out.println('"');

        char[] chars = new char[column - 1];
        Arrays.fill(chars, '_');

        System.out.print(chars);
        System.out.println("|");
    }

    static String join(String sep, Iterable<String> source) {
        final StringBuilder sb = new StringBuilder();

        for (String s : source) {
            sb.append(s).append(sep);
        }
        final int end = sb.length();
        final int start = sb.length() - sep.length();
        sb.delete(start, end);
        return sb.toString();
    }
}
